package com.yunc.common.utils;

import cn.hutool.core.bean.BeanUtil;
import com.yunc.common.oauth2.OAuth2Realm;
import com.yunc.modules.sys.entity.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;

/**
 * session容器中获取用户信息
 *
 * @author taocongcong
 * @create 2018-11-21 14:38
 */
public class ShiroUtils {

    public static Subject getSubjct() {
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout() {
        getSubjct().logout();
    }

    public static SysUser getUser() {
        // 为是么要这么写
        /*SysUser user = (SysUser) getSubjct().getPrincipal();
        return user;*/
        SysUser user = null;
        Object obj = getSubjct().getPrincipal();
        if (obj != null) {
            user = new SysUser();
            BeanUtil.copyProperties(obj, user);
        }
        return user;
    }

    public static void setUser(SysUser user) {
        Subject subject = getSubjct();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    public static void clearCachedAuthorizationInfo() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        OAuth2Realm realm = (OAuth2Realm) rsm.getRealms().iterator().next();
        realm.clearCachedAuthorizationInfo();
    }

    public static Long getUserId() {
        return getUser().getId().longValue();
    }

    public static String getLoginName() {
        return getUser().getLoginName();
    }

    public static String getIp() {
        return getSubjct().getSession().getHost();
    }

    public static String getSessionId() {
        return String.valueOf(getSubjct().getSession().getId());
    }
}
